﻿'         This file is Copyright © 2008-2012 Billy O'Neal and Aommaster
'                            All rights reserved.
'
' This file is released under the 2-Clause BSD license, included in LICENSE.TXT
'                           and on the MHWT website
Imports System.ComponentModel
Imports System.Xml.Serialization
Imports System.IO

Friend Class Topics
    Private filterShown As Boolean = False
    Private Sub populate()
        If filterShown Then
            filterBox.Text = ""
        End If
        '
        'Remove the event handlers pointing to us... we don't want our updating to go into infinite loop
        '
        RemoveHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
        RemoveHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
        filterBox.Text = ""
        popInner()
        '
        'Readd handlers now that we're done
        '
        AddHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
        AddHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
    End Sub
    Private Sub popInner()
        Dim tempcount As Integer = 0
        'knock off event handlers before clearing the listbox
        For Each item As Topic In topicListBox.Items
            RemoveHandler item.Modified, AddressOf populate
            RemoveHandler item.Deleted, AddressOf populate
        Next
        topicListBox.Items.Clear()
        'sort the list
        Dim display As List(Of Topic) = GlobalData.openTopics.ToList
        display.Sort()
        Dim tempHolder As New BindingList(Of Topic)
        For Each item As Topic In display
            tempHolder.Add(item)
        Next
        GlobalData.openTopics = tempHolder
        For Each item As Topic In GlobalData.openTopics
            topicListBox.Items.Add(item)
            AddHandler item.Modified, AddressOf populate
            AddHandler item.Deleted, AddressOf populate
            If InStr(item.Status.Trim, "day(s)") > 0 Then tempcount += 1
        Next

        logCountLabel.Text = "You have " + tempcount.ToString() + " open logs!"
    End Sub
    Private Sub popFrontend(ByVal sender As System.Object, ByVal e As System.EventArgs)
        populate()
    End Sub
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim newTopic As New Topic
        GlobalData.openTopics.Add(newTopic)
        Dim childFrm As New FixForm(newTopic)
        childFrm.MdiParent = Me.MdiParent
        childFrm.Show()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                marked.Status = "Stale"
            Next
        Else
            MsgBox("Can't mark the air stale... though it may be already!")
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                marked.Status = "Completed"
            Next
        Else
            MsgBox("All you've finished is pressing my buttons!")
        End If
    End Sub

    Private Sub btnDestroy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDestroy.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            If MsgBox("Are you sure?", MsgBoxStyle.YesNo, "Delete topic(s)") = MsgBoxResult.No Then Exit Sub
            RemoveHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
            RemoveHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
            For Each item As Topic In GlobalData.openTopics
                RemoveHandler item.Modified, AddressOf populate
                RemoveHandler item.Deleted, AddressOf populate
            Next
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                GlobalData.openTopics.Remove(marked)
                marked.delete()
            Next
            popInner()
            For Each item As Topic In GlobalData.openTopics
                AddHandler item.Modified, AddressOf populate
                AddHandler item.Deleted, AddressOf populate
            Next
            AddHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
            AddHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
        Else
            MsgBox("What do you want me to delete again?")
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            For Each newTopic As Topic In topicListBox.SelectedItems
                Dim childFrm As New FixForm(newTopic)
                childFrm.MdiParent = Me.MdiParent
                childFrm.Show()
            Next
        Else
            MsgBox("The cupboard's bare.. and there's nothing you told me to get anyway!")
        End If
    End Sub
    Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Private Sub OutstandingTopics_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        RemoveHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
        RemoveHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
        Dim fs As New IO.FileStream(System.IO.Path.Combine(Application.StartupPath, "Data.db"), IO.FileMode.Create)
        Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim temp As New DataFrontend
        formatter.Serialize(fs, temp)
        fs.Close()
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                marked.Days = DateTime.Now.Date
                marked.Status = "" '0 day(s)
            Next
        End If
    End Sub
    Private Sub closeWaitMarker_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeWaitMarker.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                marked.Days = DateTime.Now.Date
                marked.Status = "CloseWait"
            Next
        Else
            MsgBox("What kind of moderation is marking a non-existant topic for closure?")
        End If
    End Sub

    Private Sub btnWebpage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWebpage.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            For Each marked As Topic In topicListBox.SelectedItems
                marked.browse()
            Next
        Else
            MsgBox("There does not appear to be a link hidden in the air!")
        End If
    End Sub

    Private Sub topicListBox_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles topicListBox.DoubleClick
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim newTopic As Topic = CType(topicListBox.SelectedItem, Topic)
            Dim childFrm As New FixForm(newTopic)
            childFrm.MdiParent = Me.MdiParent
            childFrm.Show()
        End If
    End Sub

    Private Sub filterBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filterBox.TextChanged
        Static removed As New List(Of Topic)
        If filterBox.Text <> "" Then
            If Not filterShown Then
                filterShown = True
                btnResetFilter2.Visible = True
                topicListBox.Height -= 39
                topicListBox.Location = New System.Drawing.Point(topicListBox.Location.X, topicListBox.Location.Y + 39)
            End If
            For Each item As Topic In removed
                topicListBox.Items.Add(item)
            Next
            removed.Clear()
            popInner()
            For Each curItem As Topic In topicListBox.Items
                If curItem.ToString().ToLower().IndexOf(filterBox.Text.ToLower()) = -1 Then
                    removed.Add(curItem)
                End If
            Next
            For Each curItem As Topic In removed
                topicListBox.Items.Remove(curItem)
            Next
        End If
        If filterBox.Text = "" Then
            filterShown = False
            btnResetFilter2.Visible = False
            topicListBox.Height += 39
            topicListBox.Location = New System.Drawing.Point(topicListBox.Location.X, topicListBox.Location.Y - 39)
            For Each item As Topic In removed
                topicListBox.Items.Add(item)
            Next
            removed.Clear()
            popInner()
        End If
    End Sub

    Private Sub btnResetFilter2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResetFilter2.Click
        filterBox.Text = ""
    End Sub

    Private Sub btnCopyLinked_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCopyLinked.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim clippyString As String = "[list]"
            For Each item As Topic In topicListBox.SelectedItems
                clippyString += "[*]" + item.Link + Environment.NewLine
            Next
            clippyString.Trim()
            clippyString += Environment.NewLine + "[/list]"
            My.Computer.Clipboard.SetText(clippyString)
        End If
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                marked.Days = DateTime.Now.Date
                marked.Status = "" '0 day(s)
            Next
        End If
    End Sub

    Private Sub expTopic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles expTopic.Click
        If topicListBox.SelectedItem IsNot Nothing Then
            If topicListBox.SelectedItems.Count > 1 Then
                MsgBox("Topics can only be exported one at a time")
                Exit Sub
            End If
            Dim toSave As Topic = DirectCast(topicListBox.SelectedItem, Topic)
            Dim dlg As New SaveFileDialog
            dlg.Filter = "Topic Database (*.topic)|*.topic|XML Files (*.xml)|*.xml|Text Files (*.txt)|*.txt"
            If dlg.ShowDialog() = DialogResult.OK Then
                Dim xs As New XmlSerializer(GetType(Topic))
                Using sw As New System.Xml.XmlTextWriter(New StreamWriter(New FileStream(dlg.FileName, FileMode.Create)))
                    xs.Serialize(sw, toSave)
                End Using
            End If
        Else
            MsgBox("You are trying to export nothing. Isn't that inefficient?")
        End If
    End Sub

    Private Sub impTopic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles impTopic.Click
        Using dlg As New OpenFileDialog
            dlg.Filter = "Topic (*.topic)|*.topic|XML Files (*.xml)|*.xml|Text Files (*.txt)|*.txt"
            If dlg.ShowDialog() = DialogResult.OK Then
                Dim xs As New XmlSerializer(GetType(Topic))
                Using sw As New System.Xml.XmlTextReader(New FileStream(dlg.FileName, FileMode.Open, FileAccess.Read))
                    Dim tempO As New Topic
                    tempO = DirectCast(xs.Deserialize(sw), Topic)
                    GlobalData.openTopics.Add(tempO)
                End Using
            End If
        End Using
    End Sub

    Private Sub archivebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles archivebutton.Click
        Dim warningflag As Boolean = False
        If topicListBox.SelectedItem IsNot Nothing Then
            RemoveHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
            RemoveHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
            For Each item As Topic In GlobalData.openTopics
                RemoveHandler item.Modified, AddressOf populate
                RemoveHandler item.Deleted, AddressOf populate
            Next
            Dim tempList As New List(Of Topic)
            For Each marked As Topic In topicListBox.SelectedItems
                tempList.Add(marked)
            Next
            For Each marked As Topic In tempList
                If marked.Status = "Stale" Or marked.Status = "Completed" Then
                    Try
                        GlobalData.archive.Add(marked)
                    Catch ex As Exception
                        GlobalData.archive = New BindingList(Of Topic)
                        GlobalData.archive.Add(marked)
                    End Try

                    GlobalData.openTopics.Remove(marked)
                    marked.delete()
                Else
                    warningflag = True
                End If
                
            Next
            popInner()
            For Each item As Topic In GlobalData.openTopics
                AddHandler item.Modified, AddressOf populate
                AddHandler item.Deleted, AddressOf populate
            Next
            AddHandler GlobalData.openTopics.ListChanged, AddressOf popFrontend
            AddHandler GlobalData.openTopics.AddingNew, AddressOf popFrontend
            If warningflag = True Then
                MsgBox("Not all topics have been archived because they are not complete/stale")
            End If
        Else
            MsgBox("What do you want me to delete again?")
        End If
    End Sub
End Class
